package br.com.ac.fatureweb.soap.service;

import java.io.IOException;

import javax.inject.Inject;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebService;

import br.com.ac.fatureweb.service.NgcLeituristaBean;
import br.com.ac.fatureweb.service.NgcRoteiroBean;
import br.com.ac.fatureweb.service.ValidarAcesso;
import br.com.ac.fatureweb.utilitary.validator.OSValidator;

@WebService
public class FileServiceBean {
	/*
	 * Windows Directories
	 */
	private static final String BACKUP_WIN_DIR = "C:/ifature/backup/";

	private static final String IMAGE_WIN_DIR = "C:/ifature/fotos/";

	/*
	 * Linux Directories
	 */
	private static final String BACKUP_LINUX_DIR = "/ifature/backup/";

	private static final String IMAGE_LINUX_DIR = "/ifature/fotos/";

	/*
	 * Extensions
	 */
	private static final String BACKUP_EXTENSION = ".dbbackup";

	private static final String IMAGE_EXTENSION = ".jpg";

	@Inject
	private NgcLeituristaBean ngcLeituristaBean;

	@Inject
	private NgcRoteiroBean ngcRoteiroBean;

	/**
	 * 
	 * Recebe arquivos no formato de um array de bytes para serem gravados no
	 * servidos de arquivos.
	 * 
	 * @author José Braga Neto[josebraga.neto@cagece.com.br] 13/06/2014 -
	 *         09:11:38.
	 * 
	 * @param file
	 * @param fileName
	 * @param dir
	 * @param usuario
	 * @param senha
	 * @param imei
	 * @throws Exception
	 * @throws IOException
	 */
	@WebMethod(action = "http://service.soap.fatureweb.ac.com.br/receiveFile")
	public void receiveFile(

	@WebParam(name = "file") final byte[] file,

	@WebParam(name = "fileName") final String fileName,

	@WebParam(name = "idRoteiro") final String idRoteiro,

	@WebParam(name = "imei") final String imei,

	@WebParam(name = "usuario") final String usuario,

	@WebParam(name = "senha") final String senha) throws Exception {
		try {
			if (ValidarAcesso.execute(Long.valueOf(usuario), senha, imei,
					ngcLeituristaBean)) {
				if (fileName.contains(BACKUP_EXTENSION)) {
					if (OSValidator.isWindows()) {
						ngcRoteiroBean.uploadFileByteArray(file, fileName,
								BACKUP_WIN_DIR, Boolean.FALSE);
					} else {
						ngcRoteiroBean.uploadFileByteArray(file, fileName,
								BACKUP_LINUX_DIR, Boolean.TRUE);
					}
				} else if (fileName.contains(IMAGE_EXTENSION)) {
					if (OSValidator.isWindows()) {
						ngcRoteiroBean.uploadFileByteArray(file, fileName,
								IMAGE_WIN_DIR, Boolean.FALSE);
					} else {
						ngcRoteiroBean.uploadFileByteArray(file, fileName,
								IMAGE_LINUX_DIR, Boolean.TRUE);
					}
				}
			}

		} catch (Exception e) {
			throw new Exception(
					"Ocorreu uma falha inesperada, "
							+ "por favor entre em contato com o administrador do sistema.");
		}
	}
}